<template>
  <div class="container">
    <div class="head-top">
      <span>质押</span>
    </div>
    <div style="position: absolute;left:47%;top:45%" v-if="isLoading"><van-loading type="spinner" color="#65686C" /></div>
    <img class="banner" src="static/img/banner.png" alt="" />
    <div class="title">
      <div class="block">
        <div class="word">
          <img src="static/img/coin/income.png" alt class="coinImg" />
          <span>已收益(MDACX)</span>
        </div>
        <div class="in-num">{{totalMDACX}}</div>
      </div>
      <div class="block">
        <div class="word">
          <img src="static/img/coin/pledge.png" alt class="coinImg" />
          <span>已质押(MDPOX)</span>
        </div>
        <div class="pl-num">{{totalMDPOX}}</div>
      </div>
    </div>

    <div class="body" style="max-height: 79%;width:100%;overflow-y: scroll">
      <div class="block"  v-for="(item,index) in pledges"
           :key="index">
        <div class="left">
          <div class="l-word">收益(MDACX)</div>
          <div class="sm-word">订单号：{{item.orderNum}}</div>
        </div>
        <div class="right">
          <div class="y-num">+{{item.mdacxAmount}}</div>
          <div class="sm-word">{{item.dueTime}}</div>
        </div>
      </div>
    </div>

    <foot :index="index ? index : 3"></foot>

  </div>
</template>

<script>
import { Field, Checklist, Button } from 'mint-ui';
import Foot from '../eth/Foot';
// import {marketList} from '../../service/config'
import { mapGetters, mapActions } from 'vuex';
import { Toast } from 'vant';
import axios from 'axios';
import accountUtils from "../../service/eth/accountUtils";

export default {
  components: {
    Field,
    Checklist,
    Button,
    Foot
  },
  data() {
    return {
      isLoading: false,
      mainCoin:'',
      index: this.$route.params.index ? this.$route.params.index : 2,
      rate: this.global.rate,
      pledges:[],
      totalMDACX:0,
      totalMDPOX:0,
      currentMarketList: []
    };
  },
  created() {
    this.cloneExchangeMap = JSON.parse(JSON.stringify(this.exchangeMap));
    this.mainCoin = this.cloneExchangeMap[0];

    this.getAllPledge()
  },
  computed: {
    ...mapGetters(['wallet', 'accountIndex', 'currentAccount',"exchangeMap", 'marketList', 'marketInfo', 'marketTimeStamp', 'refresh'])
  },
  methods: {
    ...mapActions(['setWallet', 'setAccountIndex', 'setMarketInfo', 'setMarketTimeStamp', 'setRefresh']),
    async getRate() {
      this.tate = 7.1;
      // let _this = this
      // await axios.get('http://106.12.99.176:8881/getNowRate').then(resp => {
      //   _this.rate = parseFloat(resp.data.rate);
      // });
    },
    async getAllPledge() {
      let _this = this;

      console.log('执行')
      let abi = _this.mainCoin.abi;
      let mainAddr = _this.mainCoin.address;
      let mainCont = new _this.global.web3.eth.Contract(abi, mainAddr);

      let count= await mainCont.methods.getAddrPledgeCount(_this.currentAccount.address).call();

      let jobs=[]
      for(let i=0;i<count;i++){
        jobs.push(mainCont.methods.addressToPledge(_this.currentAccount.address,i).call());
      }
      let datas= await Promise.all(jobs)

      let data=[]
      for(let j=0;j<datas.length;j++){
        let beginOrder=datas[j].userAddress.substring(datas[j].userAddress.length-4)
        let centerOrder=_this.formatDateNum(new Date(datas[j].createTime*1000))
        let lastOrder=_this.getRemainderTime(datas[j].dueTime,datas[j].createTime)
        let order=beginOrder+centerOrder+lastOrder;
        let d={
          orderNum:order,
          userAddress:datas[j].userAddress,
          investAmount:datas[j].investAmount/Math.pow(10,8),
          yield:datas[j].yield/100,
          lvs:datas[j].lvs/100,
          createTime:_this.formatDateTime(new Date(datas[j].createTime*1000)),
          dueTime:_this.formatDateTime(new Date(datas[j].dueTime*1000)),
          mdacxAmount:datas[j].mdacxAmount/Math.pow(10,18)
        }

        _this.totalMDACX+=datas[j].mdacxAmount/Math.pow(10,18)
        _this.totalMDPOX+=datas[j].investAmount/Math.pow(10,8)
        data.push(d)
      }

      _this.pledges=data;
    },
    formatDateTime(date) {
      var y = date.getFullYear();

      var m = date.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      h=h < 10 ? ('0' + h) : h;
      var minute = date.getMinutes();
      minute = minute < 10 ? ('0' + minute) : minute;
      var second=date.getSeconds();
      second=second < 10 ? ('0' + second) : second;
      return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
    },
    formatDateNum(date) {
      var y = date.getFullYear()-2000;
      var m = date.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      h=h < 10 ? ('0' + h) : h;
      var minute = date.getMinutes();
      minute = minute < 10 ? ('0' + minute) : minute;
      var second=date.getSeconds();
      second=second < 10 ? ('0' + second) : second;
      return y+m+d+h+minute;
    },
   getRemainderTime(endTime,startTime){
        var runTime = parseInt(endTime - startTime);
        var day = Math.floor(runTime / 86400);
    　　return day;
    }
  },
  async mounted() {
    let _this = this;

    await this.getRate();

    if (!_this.global.web3) {
      accountUtils
        .initWeb3FromPrivateKey(_this.currentAccount.priKey)
        .then(({ web3, provider, priKey, pubKey, address }) => {
          _this.global.setWeb3(web3);
        });
    }
  }
};
</script>
<style scoped>
@import url('../../assets/css/market.css');
</style>
